package com.quectel.core.module.forum.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.forum.dao.ForumTopicBindingDao;
import com.quectel.core.module.forum.dao.ForumTopicDao;
import com.quectel.core.module.forum.dto.ForumTopicDto;
import com.quectel.core.module.forum.dto.mongo.ForumTopicCountDto;
import com.quectel.core.module.forum.entity.ForumTopicBindingEntity;
import com.quectel.core.module.forum.entity.ForumTopicEntity;
import com.quectel.core.module.forum.service.ForumTopicService;
import com.quectel.core.module.forum.service.mongo.ForumTopicCountService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/10 11:21
 */
@DubboService
public class ForumTopicServiceImpl implements ForumTopicService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ForumTopicServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> FORUM_TOPIC_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "FORUM_TOPIC_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<ForumTopicDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(FORUM_TOPIC_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private ForumTopicDao forumTopicDao;
    @Autowired
    private ForumTopicBindingDao forumTopicBindingDao;
    @Autowired
    private ForumTopicCountService forumTopicCountService;

    /**
     * @param forumTopicDto
     */
    @Override
    public void saveOrUpdate(ForumTopicDto forumTopicDto) {
        if (forumTopicDto.getId() == null) {
            Long id = save(forumTopicDto);
            forumTopicDto.setId(id);
        } else {
            updateById(forumTopicDto);
        }

        //删除关联关系
        forumTopicBindingDao.delete(new LambdaQueryWrapper<ForumTopicBindingEntity>()
                .eq(ForumTopicBindingEntity::getForumTopicId, forumTopicDto.getId()));

        if (CollectionUtils.isNotEmpty(forumTopicDto.getVillageDtoList())) {
            for (VillageDto villageDto : forumTopicDto.getVillageDtoList()) {
                ForumTopicBindingEntity forumTopicBindingEntity = new ForumTopicBindingEntity();
                forumTopicBindingEntity.setId(Snowflake.nextId());
                forumTopicBindingEntity.setForumTopicId(forumTopicDto.getId());
                forumTopicBindingEntity.setVillageId(villageDto.getId());
                forumTopicBindingDao.insert(forumTopicBindingEntity);
            }
        }
        //mongodb话题计数
        ForumTopicCountDto forumTopicCountDto = forumTopicCountService.selectByTopicId(forumTopicDto.getId());
        if(forumTopicCountDto==null){
            forumTopicCountDto =new ForumTopicCountDto();
            forumTopicCountDto.setTopicId(forumTopicDto.getId());
            forumTopicCountService.save(forumTopicCountDto);
        }

    }

    @Override
    public ForumTopicDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                FORUM_TOPIC_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public ForumTopicDto selectById(Long id){
            ForumTopicEntity entity = forumTopicDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,ForumTopicDto.class));
    }

    @Override
    public List<ForumTopicDto> queryList(Map<String,Object> params){
        List<ForumTopicEntity> list = forumTopicDao.queryList(params);
        List<ForumTopicDto> result =  CopyUtils.copyList(list,ForumTopicDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private ForumTopicDto paddingField(ForumTopicDto dto){
        if (dto != null){

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return forumTopicDao.queryTotal(params);
    }

    @Override
    public Long save(ForumTopicDto dto){
        ForumTopicEntity entity = CopyUtils.copyObj(dto,ForumTopicEntity.class);
        entity.setId(Snowflake.nextId());
        forumTopicDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(ForumTopicDto dto){
        ForumTopicEntity entity = CopyUtils.copyObj(dto,ForumTopicEntity.class);

        forumTopicDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(ForumTopicDto dto) {
       ForumTopicEntity entity = CopyUtils.copyObj(dto,ForumTopicEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, forumTopicDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        forumTopicDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
